let hasDangerArea = false;
let modelmes = wx.getSystemInfoSync().model;
let checkModal = ['iPhone X', 'iPhone 11', 'iPhone 12', 'iPhone 13', 'iPhone 14', 'iPhone 15', 'iPhone 16'];//需要匹配设置底部危险区域的机型
for (let i = 0; i < checkModal.length; i++) {
  if (modelmes.search(checkModal[i]) !== -1) {
    hasDangerArea = true;
    break;
  }
  if (i === checkModal.length - 1) {
    hasDangerArea = false;
  }
}

Component({
  data: {
    openUrl: '',
  },
  shareUrl: '',
  lifetimes: {
    ready() {
      // 传入url参数
      let pages = getCurrentPages();
      let currentPage = pages[pages.length - 1];

      let originUrl = decodeURIComponent(currentPage.options.originUrl);

      // 向下兼容 accessToken + userId > session
      let accessToken = getApp().globalData.lsAccessToken;
      let userId = getApp().globalData.lsUserId;

      let tn = getApp().globalData.tn;
      let session = encodeURIComponent(JSON.stringify({
        appType: getApp().globalData.sId,
        loginId2: userId,
        loginId: userId,
      }));

      let vconsole = getApp().globalData.debug;
      let openUrl = '';
      this.shareUrl = originUrl;
      // 添加accessToken、session、hasDangerArea、tn、userId参数
      if (originUrl.indexOf("?") > -1) {
        openUrl = `${originUrl}&tn=${tn}&_accessToken=${accessToken}&_userId=${userId}&_session=${session}`;
      } else {
        openUrl = `${originUrl}?tn=${tn}&_accessToken=${accessToken}&_userId=${userId}&_session=${session}`;
      }
      if(hasDangerArea) openUrl += "&hasDangerArea=1";
      if(vconsole) openUrl += "&vconsole=1";
      this.setData({ openUrl })

      console.log("打开乐智H5:", this.data.openUrl);

      wx.hideShareMenu();
      this.onloadHandle();
    }
  },
  pageLifetimes: {
    show() {
      if (!this.data.openUrl) return;
      console.log(this.data.openUrl);
      this.setData({ openUrl: this.data.openUrl + "#onshow" });
    }
  },
  methods: {
    onloadHandle() {
      this.setNavigation();
    },
    messageHandle(e) {
      let data = e.detail.data || [];
      this.triggerEvent('message', data)
    },
    setNavigation() {
      let url = this.data.openUrl;
      let config;
      // 加载远程导航栏
      wx.request({
        url: url.substring(0, url.indexOf('.html')) + '/page.json',
        success(res) {
          let defaultConfig = res.data && res.data.navigation || {};
          let tnConfig = defaultConfig[getApp().globalData.tn] || {};
          config = { ...defaultConfig, ...tnConfig };
        },
        complete() {
          let pages = getCurrentPages();
          let cPage = pages[pages.length - 1];
          if (!cPage || cPage.route !== "pages/h5/common/main") return;

          config.frontColor && wx.setNavigationBarColor(config);
          config.title && wx.setNavigationBarTitle(config);
        }
      });
    }
  }
});